<template>
  <BModal
    :confirm-loading="submitLoading"
    :height="500"
    :title="isEdit ? '编辑连接' : '新建连接'"
    :visible="visible"
    :width="700"
    @cancel="closeClick"
    @ok="dbSaveClick"
  >
    <a-form-model ref="ruleForm" :label-col="labelCol" :model="dbForm" :rules="formRules" :wrapper-col="wrapperCol">
      <a-row>
        <a-col :span="24">
          <a-form-model-item
            ref="dbType"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 16 }"
            label="数据库类型"
            prop="dbType"
          >
            <a-select v-model="dbForm.dbType" placeholder="请选择数据库" style="width: 100%">
              <a-select-option v-for="item in dbTypeList" :key="item.value" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item
            ref="connectName"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 16 }"
            label="连接名称"
            prop="connectName"
          >
            <a-input v-model.trim="dbForm.connectName" placeholder="自定义连接名称" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item ref="host" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }" label="主机IP" prop="host">
            <a-input v-model.trim="dbForm.host" placeholder="连接主机IP" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item ref="port" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }" label="端口" prop="port">
            <a-input v-model.trim="dbForm.port" placeholder="" type="number" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item
            ref="dbName"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 16 }"
            label="数据库名"
            prop="dbName"
          >
            <a-input v-model.trim="dbForm.dbName" placeholder="" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item
            ref="username"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 16 }"
            label="用户名"
            prop="username"
          >
            <a-input v-model.trim="dbForm.username" placeholder="" />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-model-item
            ref="password"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 16 }"
            label="密码"
            prop="password"
          >
            <a-input v-model.trim="dbForm.password" placeholder="" type="password" />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
  </BModal>
</template>

<script>
import { VXETable } from 'vxe-table/lib/v-x-e-table';
import { addDatabase, getDatabase } from '@bdp/sl/dataSecurity/api';

export default {
  components: {},
  name: 'DbForm',
  data() {
    return {
      labelCol: { span: 3 },
      wrapperCol: { span: 20 },
      visible: false,
      dbTypeList: [
        { label: 'MySQL', value: 'MySQL' },
        { label: 'PostgreSQL', value: 'PostgreSQL' },
        { label: '达梦数据库', value: 'DMS' },
      ],
      submitLoading: false,
      isEdit: false,
      dbForm: {
        id: null,
        dbType: null,
        connectName: '',
        host: '',
        port: '',
        dbName: '',
        username: '',
        password: '',
        maxFileNum: 10,
      },
      formRules: {
        dbType: [{ required: true, message: '不能为空', trigger: 'blur' }],
        connectName: [{ required: true, message: '请输入连接名称', trigger: 'blur' }],
        host: [
          { required: true, message: '请输入主机IP', trigger: 'blur' },
          {
            validator: this.validateIPAddress,
            trigger: 'blur',
          },
        ],
        port: [
          { required: true, message: '请输入端口', trigger: 'blur' },
          {
            validator: this.validatePort,
            trigger: 'blur',
          },
        ],
        dbName: [{ required: true, message: '请输入数据库名', trigger: 'blur' }],
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      },
    };
  },
  created() {},
  methods: {
    validateIPAddress(rule, value, callback) {
      const ipRegex =
        /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
      if (value === '') {
        callback(new Error('请输入 IP 地址'));
      } else if (!ipRegex.test(value)) {
        callback(new Error('请输入有效的 IP 地址'));
      } else {
        callback();
      }
    },
    validatePort(rule, value, callback) {
      if (value === null || value === undefined) {
        callback(new Error('请输入端口号'));
      } else if (isNaN(value) || value < 0 || value > 65535) {
        callback(new Error('请输入 0 到 65535 之间的端口号'));
      } else {
        callback();
      }
    },
    init(isEdit, row) {
      this.visible = true;
      this.isEdit = isEdit;
      if (isEdit) {
        // 编辑
        this.submitLoading = true;
        getDatabase(row.id)
          .then((res) => {
            this.dbForm = res.data;
            this.submitLoading = false;
          })
          .catch(() => {
            this.submitLoading = false;
          });
      } else {
        this.reset();
      }
    },
    // 重置字段
    reset() {
      this.dbForm = {
        id: null,
        dbType: null,
        connectName: '',
        host: '',
        port: '',
        dbName: '',
        username: '',
        password: '',
        maxFileNum: 10,
      };
    },
    // 保存
    async dbSaveClick() {
      this.submitLoading = true;
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          console.log('====');
          addDatabase(this.dbForm).then((res) => {
            if (res.code === 0) {
              VXETable.modal.message({ content: '保存成功', status: 'success' });
              this.dbFormShow = false;
              this.$emit('success');
              this.$emit('close');
            }
            this.submitLoading = false;
          });
        } else {
          this.submitLoading = false;
          return false;
        }
      });
    },
    closeClick() {
      this.dbFormShow = false;
      this.$emit('close');
    },
  },
};
</script>
